﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WinFormsApp_SetAutoStartup
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnSetOk_Click(object sender, EventArgs e)
        {
            RegCompStartRun(true, txtFullPath.Text.Trim());
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            RegCompStartRun(false, txtFullPath.Text.Trim());
        }

        private void RegCompStartRun(bool cmd, string argPath)
        {
            lblDisplay.Text = "";

            string starupPath = argPath;
            if (string.IsNullOrEmpty(argPath))
            {
                //获取当前可执行程序的全路径
                starupPath = Application.ExecutablePath;
            }

            //表示Window注册表中项级节点,读取 Windows 注册表基项HKEY_LOCAL_MACHINE 
            Microsoft.Win32.RegistryKey loca = Microsoft.Win32.Registry.LocalMachine;
            Microsoft.Win32.RegistryKey run = loca.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
            try
            {
                //SetValue:存储值的名称
                if (cmd)
                {
                    if (run.GetValue("AutoStartupTestWinFormApp") == null)
                    {
                        run.SetValue("AutoStartupTestWinFormApp", starupPath);//加入注册，参数一为注册节点名称(随意)   
                        lblDisplay.Text = "设置成功!";
                    }
                }
                else
                {
                    if (run.GetValue("AutoStartupTestWinFormApp") != null)
                    {
                        run.DeleteValue("AutoStartupTestWinFormApp", false);//删除该注册节点     
                        lblDisplay.Text = "取消设置成功!";
                    }
                }
                loca.Close();
                //run.Close();//此句是还原修改，需要屏蔽
            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.Message.ToString(), "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}
